package cn.ytr.project.web.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AdminUserLoginFilter implements Filter{
	//需要拦截的uri
	List<String> unCheckUris;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest requestHttp = (HttpServletRequest) request;
		HttpServletResponse responseHttp = (HttpServletResponse) response;
		
		request.setCharacterEncoding("UTF-8");

		//用户登录的 session
		HttpSession session = requestHttp.getSession();
		Object userSession = session.getAttribute("USER_IN_SESSION");
		
		//当前url
		String url = requestHttp.getRequestURI();
		System.out.println("uri：-------------------------" + url);
		System.out.println("userSession：" + userSession);
		System.out.println("this.unCheckUris：" + this.unCheckUris);
		System.out.println("this.unCheckUris.contains(url)《--------------------》" + this.unCheckUris.contains(url));
		
		//判断放行 /login.jsp 放行，其他的要判断 userSession
		if (!this.unCheckUris.contains(url)) {
			if (userSession == null) {
				System.out.println("无session，到登录页");
				responseHttp.sendRedirect("/login.jsp");
				return;
			}
		}
		System.out.println();
		chain.doFilter(request, response);
		
		
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		//获取 web.xml 初始参数 checkUris 需要拦截的
		String unCheckUrisString = config.getInitParameter("unCheckUris");
		System.out.println(unCheckUrisString);
		String[] unCheckUrisStringArr = unCheckUrisString.split(",");
		List<String> unCheckUris = Arrays.asList(unCheckUrisStringArr);
		this.unCheckUris = unCheckUris;
		
	}

}
